<template>
  <d2-container>
  <div class="app-container">
    <el-container :style="'height:'+containerHeight+'px'">
      <el-main class="bg-white el-aside">
        <el-row>
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <div style="font-size:15px;display:inline-block; float:left;">
                <!--<el-form-item label="区域" label-width="40px">-->
                  <!--<el-input placeholder="请选择区域信息"-->
                            <!--style="width: 250px;"-->
                            <!--class="filter-item"-->
                            <!--size="small"-->
                            <!--:suffix-icon="showTree?'el-icon-arrow-up':'el-icon-arrow-down'"-->
                            <!--@click.native="deptogglePanel($event)"-->
                            <!--v-model="currentbuildInfo.buildingName">-->
                    <!--<template slot="prepend">区域选择</template>-->
                  <!--</el-input>-->
                  <!--<div v-if="showTree" class="objectTree w-160" ref="suoShuMenTree">-->
                    <!--<el-tree-->
                      <!--:style="'height:'+containerHeight+'px'"-->
                      <!--ref="buildTree"-->
                      <!--highlight-current-->
                      <!--node-key="buildingId"-->
                      <!--:data="buildDataList"-->
                      <!--:check-on-click-node="true"-->
                      <!--:check-strictly="true"-->
                      <!--:expand-on-click-node="false"-->
                      <!--:props="menuListTreeProps"-->
                      <!--@node-click="selectBuild"-->
                      <!--default-expand-all-->
                    <!--&gt;</el-tree>-->
                  <!--</div>-->
                <!--</el-form-item>-->
                <el-form-item label="分类" label-width="40px">
                  <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini">
                    <el-option
                      v-for="(item, index) in meterTypeList" :key="index"
                      :label="item.paramValue"
                      :value="item.paramKey">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="日期" label-width="40px">
                    <el-date-picker
                      v-model="dataForm.date"
                      placeholder="时间范围"
                      style="width: 150px;"
                      class="filter-item"
                      size="mini"
                      :type="dataForm.dateType"
                      suffix-icon="el-icon-date"
                      clearable
                      @keyup.enter.native="getPowerDataList"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="dataForm.dateType" size="mini">
                      <el-radio-button :label="item.date" v-for="(item, index) in Config.searchDate" :key="index">
                        {{item.label}}
                      </el-radio-button>
                    </el-radio-group>
                </el-form-item>
              </div>
              <div style="display:inline-block; float:right;">
                <el-form-item>
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getPowerDataList"
                  >查询</el-button>
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-download"
                    size="mini"
                    @click="exoprtData"
                  >导出</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-row>
        <div style="margin-top:20px;">
          <el-row>
            <el-col :span="24" style="width: 100%;overflow:auto;" >
              <el-table :data="dataList" :height="chartHeight" border style="width: 100%;overflow:visible;"  :span-method="objectSpanMethod">
                <!-- <el-table-column prop="index" header-align="center" align="center"  width="70" label="序号"></el-table-column> -->
                <el-table-column
                  prop="ObjName"
                  header-align="center"
                  align="center"
                  label="区域"
                ></el-table-column>
                <el-table-column
                  prop="rentName"
                  header-align="center"
                  align="center"
                  label="租户">
                </el-table-column>
                <!--<el-table-column-->
                  <!--prop="meterTypeName"-->
                  <!--header-align="center"-->
                  <!--align="center"-->
                  <!--label="分类"-->
                  <!--width="70"-->
                <!--&gt;</el-table-column>-->
                <el-table-column
                  prop="meterName"
                  header-align="center"
                  align="center"
                  label="计量器具名称"
                ></el-table-column>
                <el-table-column
                  prop="date"
                  header-align="center"
                  align="center"
                  label="时间"
                ></el-table-column>
                <el-table-column :label="item.label+`(${unit})`" v-for="(item, index) in header" :key="item.label"  align="center" >
                  <template slot-scope="scope">
                    <span v-for="(item2,index2) in scope.row.collectList" v-if="index2 == index"> {{ scope.row.collectList[index2].dailySum }} </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="val"
                  header-align="center"
                  align="center"
                  :label="`总用量(${unit})`"
                >
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                      <p v-for="(item, index) in scope.row.collectList">{{ item.collectType|collectName(collectTypeList) }}:{{ item.dailySum }}</p>
                      <div slot="reference" class="name-wrapper">
                        <el-tag size="medium">{{ scope.row.val }}</el-tag>
                      </div>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="fee"
                  header-align="center"
                  align="center"
                  label="费用(元)"
                ></el-table-column>
                <el-table-column
                prop="avgfee"
                header-align="center"
                align="center"
                :label="`平均单价(元/${unit})`"
              >
                  <template slot-scope="scope">
                    {{ (scope.row.fee/scope.row.val).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="totalfee"
                  header-align="center"
                  align="center"
                  label="总费用(元)"
                ></el-table-column>
              </el-table>
              <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="page.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.size"
                :total="page.total"
                layout="total, sizes, prev, pager, next, jumper">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-main>
      <el-aside class="tree-area">
        <el-tabs v-model="activeName">
          <el-tab-pane label="区域" name="2">
            <el-tree
              style="margin-top: 10px"
              ref="buildTree"
              :show-checkbox="true"
              highlight-current
              node-key="buildingId"
              :check-on-click-node="true"
              :check-strictly="false"
              :data="buildDataList"
              :expand-on-click-node="false"
              :props="menuListTreeProps"
              @check="selectBuild"
              default-expand-all
            ></el-tree>
            <!--<el-tree-->
              <!--:style="'height:'+containerHeight+'px'"-->
              <!--ref="buildTree"-->
              <!--highlight-current-->
              <!--node-key="buildingId"-->
              <!--:data="buildDataList"-->
              <!--:check-on-click-node="true"-->
              <!--:check-strictly="true"-->
              <!--:expand-on-click-node="false"-->
              <!--:props="menuListTreeProps"-->
              <!--@node-click="selectBuild"-->
              <!--default-expand-all-->
            <!--&gt;</el-tree>-->
          </el-tab-pane>
        </el-tabs>

      </el-aside>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import * as Echarts from 'echarts'
import Config from "@/utils/config"
import Minix from '../power/mixin'
export default {
  name: "areaPage",
  mixins:[Minix],
  data() {
    return {
      activeName:'2',
      header:[],
      Config:Config,
      activeName:'2',
      dataForm: {
        date:new Date(),
        dateType:'date',
        energyType:this.$meterType.ELECTRIC,
        flag:''
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      buildTreeProps: {
        label: "buildingName",
        children: "children"
      },
      orgTreeProps: {
        label: "organizationName",
        children: "children"
      },
      unit:'',
      dataList:[],
      dataBuildingList: [],
      dataOrgList:[],
      meterTypeList:[],
      currentSelectBuildInfoList:[],
      currentSelectDepartInfoList:[],
      departTableDataList:[],
      sourceData:[],
      buildDataList: [],
      collectTypeList:[],
      showTree:false,
      currentbuildInfo: {
        buildingName:'',
      },
      menuListTreeProps: {
        label: "buildingName",
        children: "children"
      },
      spanArr:[],
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 325;
    }
  },
  created() {
    this.queryStatic("METER_TYPE");
    this.getBuildDataList();
    this.queryCollectType();
  },
  filters: {
    collectName: function (value, statusList) {
      for (let i = 0; i < statusList.length; i++) {
        if (statusList[i].collectType === value) {
          return statusList[i].collectName;
        }
      }
    }
  },
  methods: {
    collectName: function (value) {
      for (let i = 0; i < this.collectTypeList.length; i++) {
        if (this.collectTypeList[i].collectType === value) {
          return this.collectTypeList[i].collectName;
        }
      }
    },
    /**
     * 获取采集分项
     */
    queryCollectType() {
      let params = {
        'state': '1' ,
        "customerId":this.$cookie.get('customer_id'),
        'page': 1,
        'limit': 10000,
      }
      this.$http({
        url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({data}) => {
        if (data && data.code === 0) {
        this.collectTypeList =  data.page.list
      } else {
        this.collectTypeList = [];
      }
      });
    },
    getSpanArr(data) {
      this.spanArr =[]
      let OrderObj = {}
      data.forEach((element, index) => {
        element.rowIndex = index
      if (OrderObj[element.rentKey]) {
        OrderObj[element.rentKey].push(index)
      } else {
        OrderObj[element.rentKey] = []
        OrderObj[element.rentKey].push(index)
      }
    })

      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      for (let k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.spanArr.push(OrderObj[k])
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 8) 
      {
        for (let i = 0; i < this.spanArr.length; i++) 
        {
          let element = this.spanArr[i]
          for (let j = 0; j < element.length; j++) 
          {
            let item = element[j]
            if (rowIndex == item) 
            {
              if (j == 0) 
              {
                return {
                  rowspan: element.length,
                  colspan: 1
                }
              } else if (j != 0) 
              {
                return {
                  rowspan: 0,
                  colspan: 0
                }
              }
            }
          }
        }
      }
    },
    // 获取数据列表
    getBuildDataList() {
      this.$http({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          page: 1,
          limit: 10000,
          customerId: this.$cookie.get("customer_id"),
          projectid:this.$cookie.get("cuuren_projectId")
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
        this.currentbuildInfo =data.menuList[0],
        this.buildDataList = Util.treeDataTranslate(
          data.menuList,
          "buildingId",
          "parentBuildingId"
        );
        this.getPowerDataList()
      } else {
        this.buildDataList = [];
      }
    });
    },
    // selectBuild (data) {
    //   this.currentbuildInfo = data;
    //   this.showTree = false
    // },
    selectBuild (data, checked, indeterminate) {
      /*
      if(checked){
        this.$refs.buildTree.setCheckedNodes([]);
        this.currentbuildInfo = data;
        //查询设备列表
        this.$refs.buildTree.setChecked(data.buildingId,checked);
        this.showTree = false
      }
      */
      this.currentSelectBuildInfoList = this.$refs.buildTree.getCheckedNodes();
    },
    deptogglePanel (event) {
      event || (event = window.event)
      event.stopPropagation
        ? event.stopPropagation()
        : (event.cancelBubble = true)
      this.showTree ? this.dephide() : this.depshow()
    },
    depshow () {
      this.showTree = true;
      document.addEventListener('click', this.dephidePanel, false)
    },
    dephide () {
      this.showTree = false
      document.addEventListener('click', this.dephidePanel, false)
    },
    dephidePanel (e) {
      if (
        this.$refs.suoShuMenTree &&
        !this.$refs.suoShuMenTree.contains(e.target)
      ) {
        this.dephide()
      }
    },
    sizeChangeHandle(size){
      this.page.size = size;
      this.handleDataList();
    },
    currentChangeHandle(page){
      this.page.page = page;
      this.handleDataList();
    },
    exoprtData(){


      let header=['区域','租户','计量器具名称','时间',`总用量(${this.unit})`,'费用(元)',`平均单价(元/${this.unit})`,'总费用(元)'];
      let props=['ObjName','rentName','meterName','date','val','fee','avgfee','totalfee'];
      let fileName=`${this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}预付费报表`;
      this.export2Excel(header,props,fileName,this.sourceData)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = JSON.parse(JSON.stringify(dataList));
      let sumVal = list.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.val;
      }, 0);
      let sumfee = list.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.fee;
      }, 0);
      list.push({
        "ObjName":'合计',
        "val":sumVal,
        "fee":sumfee
      })

        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    getSummaries(param) {
      const { columns, data } = param;
      let sumVal = this.sourceData.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.val;
      }, 0);
      let sumfee = this.sourceData.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.fee;
      }, 0);
      return ['合计','','','',sumVal,sumfee];
    },
    //选中部门
    selectDepart(){
      this.currentSelectDepartInfoList = this.$refs.departTree.getCheckedNodes();
    },
    // //选中设备
    // selectBuild(){
    //   this.currentSelectBuildInfoList = this.$refs.buildTree.getCheckedNodes();
    // },
    // 获取区域树
    getBuildInfoList() {
      this.$http({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          customerId: this.$cookie.get("customer_id"),
          projectid:this.$cookie.get("cuuren_projectId")
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataBuildingList =  Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
        } else {
          this.dataBuildingList = [];
        }
      });
    },
    // 获取部门数据列表
    getDepartList () {
      this.$http({
        url: this.$http.adornUrl("/ecs/ecsorganizationinfo/select"),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          "customerId":this.$cookie.get('customer_id')
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataOrgList =Util.treeDataTranslate(data.menuList,'organizationId','parentOrgId')
        } else {
          this.dataOrgList = []
        }
      })
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$http({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$cookie.get('customer_id')
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.unit = data.page[0].paramExt;
        } else {
          this.meterTypeList = []
        }
       // this.getPowerDataList();
      });
    },
    getPowerDataList() {
      this.page.page = 1;
      this.sourceData = [];
      this.dataList = [];
      let currentSelectInfo = [];
      if(this.currentSelectBuildInfoList&&this.currentSelectBuildInfoList.length>0)
      {
            this.currentSelectBuildInfoList.forEach(ele=>{
                currentSelectInfo.push(ele.buildingId);
            })
      }
      let params = {
          customerId: this.$cookie.get("customer_id"),
          meterType:this.dataForm.energyType , //能耗分类
          buildingId: this.currentbuildInfo.buildingId,
          buildingIds: currentSelectInfo,
          dateType :parseInt(this.Config.searchDate.find(ele=>ele.date==this.dataForm.dateType).typeDesc)+2,// 3:按天, 4:按月 5:年
          date:Util.dateFormat(this.Config.searchDate.find(ele=>ele.date==this.dataForm.dateType).formatStr,new Date(this.dataForm.date)), //日期
          // objIds: [7,9],
          // date: '2020-06',
          // dateType: '4',
          // objType: '2',
          // meterType: '1',
          // customerId: this.$cookie.get("customer_id")

      }
      this.$http({
        url: this.$http.adornUrl('/ecm/report/consume'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then(({data}) => {
        if (data && data.code === 0) {
          //console.log('所有数据',data.data)
          if(data.data&&data.data.length>0){
            this.sourceData =data.data;
            if(this.sourceData.length>0){
              this.page.total = this.sourceData.length;
              this.sourceData.forEach(ele=>{
                ele.meterTypeName = this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue;
                if(ele.val == 0)
                {
                    ele.avgfee = 0
                }
                else
                {
                    ele.avgfee = (ele.fee/ele.val).toFixed(2)
                }
              })

            }
            else{
              this.page.total =0;
              this.dataList = [];
            }
            this.handleDataList()
          }
        }
      });
    },
    handleDataList(){
      this.header=[]
      this.spanArr =[]
      if(this.sourceData.length>0){
        let totalPage = Math.ceil(this.sourceData.length/this.page.size);
        if(this.page.page<=totalPage){
          if(this.page.page*this.page.size>=this.sourceData.length){
             this.dataList = this.sourceData.slice((this.page.page-1)*this.page.size,this.sourceData.length);
          }
          else{
            this.dataList = this.sourceData.slice((this.page.page-1)*this.page.size,this.page.page*this.page.size);
          }
          var objlist = this.dataList[0].collectList;
          for(var i=0;i< objlist.length;i++){
            var obj = objlist[i];
            obj['label'] = this.collectName(objlist[i].collectType)
            this.header.push(obj)
          }
          console.log(this.header)
          this.getSpanArr(this.dataList)
        }
      }
    }
  },
  watch:{
    'dataForm.energyType':function(newV,oldV){
      this.unit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
  }
};
</script>

<style scoped>
.tree-area { background-color: rgba(0, 0, 0, 0.1);
  width: 250px !important;
  /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
  padding-top: 10px;
  padding-left: 15px;
}
.bg-white {
  box-shadow: 0px 0px 2px 2px #f7f6f6;
}
.el-tree-node__content {
  height: 30px !important;
}
.busi-chart{
    width: 100%;
    height: 250px;
    margin-top: 10x;
    margin-bottom: 20px;
}
.el-form-item{
  margin-bottom: 0px;
}
.search-area{
   display:flow-root;
   margin-bottom: 10px;
   border: 1px solid #e8e8e8;
   border-left: none;
   border-right: none;
   padding: 10px 0px 10px 0px;
}
.objectTree {
  margin-left: 89px;
  position: absolute;
  overflow: auto;
  z-index: 100;
  height: 200px;
  /* border: 1px solid #ddd; */
  line-height: normal;
  z-index: 204;
  box-shadow: 0px 0px 1px 1px #e2dfdf;
  margin-top: 3px;
  border-radius: 4px;
  background-color: white;
}
.w-160{
  width: 160px
}
</style>
